﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace FB.Data
{
    public interface IUnitOfWorkBase: IDisposable
    {
        int SaveChanges();
        int SaveChanges(bool AutoRefresh);
    }

    public class UnitOfWorkBase<TContext> : IUnitOfWorkBase where TContext : FB.Data.Models.DbContextBase, new()
    {
        protected readonly TContext _context;
        private bool _disposed = false;

        public TContext DbContext
        {
            get { return this._context; }
        }

        public UnitOfWorkBase() { this._context = new TContext(); }
        public UnitOfWorkBase(TContext context) { this._context = context; }

        /// <summary>
        /// Saves all changes made in this context to the underlying database.
        /// </summary>
        /// <returns>The number of objects written to the underlying database.</returns>
        public int SaveChanges()
        {
            return SaveChanges(false);
        }

        /// <summary>
        /// Saves all changes made in this context to the underlying database.
        /// </summary>
        /// <param name="AutoRefresh"></param>
        /// <returns>The number of objects written to the underlying database.</returns>
        public int SaveChanges(bool AutoRefresh)
        {
            return _context.SaveChanges(AutoRefresh);            
        }


        //protected virtual IRepository<T> GetRepository<T>(ref IRepository<T> _rpo) where T : class
        //{
        //    if (_rpo == null)
        //        _rpo = new Repository<TContext, T>(_context);
        //    return _rpo;
        //}


        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }

}

